import { NMTopoBaseCommand } from '@app-cad/environments/nextmesh/types/command';
import { DeleteMode, Pick3DOptions, TopoDialogProps } from '../type';

import {
  CENTEREVENTS,
  CommandDialog,
  EventsRes,
  KEYBOARD_KEY,
} from '@amcax/base';
import { Picker3D, PickerMgr } from '@amcax/renderer';
import i18n from '@app-cad/common/utils/i18next';
import { documentV2 } from '@app-cad/environments/nextmesh/domain';
import { nextmeshEventCenter } from '@app-nextmesh/common/events/EventCenter';
import { useEffect } from 'react';

import { RJSFSchema, UiSchema } from '@rjsf/utils';
import { RadioButtonFields } from '../cmd-common/radioButtonFields';

import {
  CommandFormWrapper,
  NonDialogCommandForm,
} from '@app-base/common/components/command-form';
import { CommandFormFooter } from '@app-base/common/components/command-form/footer';
import { useRef, useState } from 'react';
// 几何清理：删除
function GeometryDeleteEntity({ onClose, title }: TopoDialogProps) {
  const picker = PickerMgr.getPicker<Picker3D>('3d');
  const [formData, setFormData] = useState({
    mode: DeleteMode.Vertex,
  });
  const [deleteText, setDeleteText] = useState('点'); // 初始提示文本
  const pickTypeRef = useRef<Pick3DOptions>({
    point: true,
  });
  useEffect(() => {
    nextmeshEventCenter()
      .setState('cmdTopoDelete')
      .on(CENTEREVENTS.POINTERMOVE, onPointMove)
      .on(CENTEREVENTS.POINTERUP, onPointUp)
      .on(CENTEREVENTS.KEYUP, onKeyUp);
    return () => {
      nextmeshEventCenter()
        .off(CENTEREVENTS.POINTERUP, onPointUp)
        .off(CENTEREVENTS.POINTERDOWN, onPointMove)
        .off(CENTEREVENTS.KEYUP, onKeyUp)
        .setDefault();
    };
  }, []);
  useEffect(() => {
    switch (formData.mode) {
      case DeleteMode.Vertex:
        setDeleteText('点');
        pickTypeRef.current = { point: true };
        break;
      case DeleteMode.Edge:
        setDeleteText('边');
        pickTypeRef.current = { line: true };
        break;
      case DeleteMode.Face:
        setDeleteText('面');
        pickTypeRef.current = { face: true };
        break;
      case DeleteMode.Volume:
        setDeleteText('体');
        pickTypeRef.current = { model: true };
        break;
      default:
        setDeleteText('点');
        break;
    }
  }, [formData.mode]);
  const onPointMove = (e: EventsRes) => {
    picker.pick(e, pickTypeRef.current);
  };
  const onPointUp = async (e: EventsRes) => {
    if (e.button.onLeft) {
      const info = picker.pick(e, pickTypeRef.current);
      const source: string[] = [];
      let params = {
        mode: null,
        source: null,
      };
      if (pickTypeRef.current?.point) {
        source.push(info.vertexId);
        params = {
          mode: DeleteMode.Vertex,
          source,
        };
      } else if (pickTypeRef.current?.line) {
        source.push(info.edgeId);
        params = {
          mode: DeleteMode.Edge,
          source,
        };
      } else if (pickTypeRef.current?.face) {
        source.push(info.meshId);
        params = {
          mode: DeleteMode.Face,
          source,
        };
      } else if (pickTypeRef.current?.model) {
        source.push(info.objInfo.dxid);
        params = {
          mode: DeleteMode.Volume,
          source,
        };
      }

      await documentV2.deleteEntity(params);
    } else {
      onClose();
    }
  };
  function onKeyUp(e: EventsRes<KeyboardEvent>) {
    if (e.key === KEYBOARD_KEY.ESC) {
      onClose();
    }
  }
  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      mode: {
        type: 'string',
        enum: [
          DeleteMode.Vertex,
          DeleteMode.Edge,
          DeleteMode.Face,
          DeleteMode.Volume,
        ],
        default: DeleteMode.Vertex,
      },
    },
  };
  const uiSchema: UiSchema = {
    mode: {
      'ui:field': RadioButtonFields,
      'ui:options': {
        options: [
          {
            value: DeleteMode.Vertex,
            label: '点',
          },
          {
            value: DeleteMode.Edge,
            label: '边',
          },
          {
            value: DeleteMode.Face,
            label: '面',
          },
          {
            value: DeleteMode.Volume,
            label: '体',
          },
        ],
      },
    },
  };
  return (
    <CommandDialog
      title={title}
      placement='topLeft'
      onClose={onClose}>
      <NonDialogCommandForm
        schema={schema}
        extraUiSchema={uiSchema}
        formData={formData}
        showCancel={false}
        onChange={(data) => {
          setFormData(data.formData);
        }}
        showSubmit={false}></NonDialogCommandForm>
      <div className='description-text'>{'请选择删除的' + deleteText}</div>
      <CommandFormWrapper>
        <CommandFormFooter
          onClose={onClose}
          cancelText='关闭'
          showSubmit={false}
        />
      </CommandFormWrapper>
    </CommandDialog>
  );
}

export const cmdTopoDelete: NMTopoBaseCommand = {
  id: 'CmdTopoDelete',
  label: 'command.topo.delete',
  icon: 'commands/curved/point',
  create: (label: string, onClose: () => void) => (
    <GeometryDeleteEntity
      title={i18n.t(label)}
      onClose={onClose}
    />
  ),
};
